/**
 * contact服务实现
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.service.impl;


import com.sxf.crm.dto.ContactRequest;
import com.sxf.crm.entity.Contact;
import com.sxf.crm.entity.ContactDepartment;
import com.sxf.crm.entity.Department;
import com.sxf.crm.entity.User;
import com.sxf.crm.enums.DeleteStatus;
import com.sxf.crm.exception.ResourceNotFoundException;
import com.sxf.crm.repository.ContactDepartmentRepository;
import com.sxf.crm.repository.ContactRepository;
import com.sxf.crm.repository.CustomerRepository;
import com.sxf.crm.repository.DepartmentRepository;
import com.sxf.crm.service.ContactService;
import com.sxf.crm.service.CustomerLogService;
import com.sxf.crm.service.UserService;

import lombok.RequiredArgsConstructor;  
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/6/1
 */
@Service
@RequiredArgsConstructor
@Transactional
public class ContactServiceImpl implements ContactService {

    private final ContactRepository contactRepository;
    private final ContactDepartmentRepository contactDepartmentRepository;
    private final CustomerRepository customerRepository;
    private final DepartmentRepository departmentRepository;
    private final UserService userService;
    private final CustomerLogService customerLogService;

    @Override
    @Transactional(readOnly = true)
    public Page<Contact> getContacts(String name, Pageable pageable) {
        return contactRepository.findAll(name, DeleteStatus.NOT_DELETED, pageable);
    }

    @Override
    @Transactional(readOnly = true)
    public Contact getContact(Long id) {
        return contactRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Contact not found with id: " + id));
    }

    @Override
    @Transactional
    public Contact createContact(ContactRequest request,Long currentUserId) {
        Contact contact = new Contact();
        contact.setName(request.getName());
        contact.setPhone(request.getPhone());
        contact.setEmail(request.getEmail());
        contact.setPosition(request.getPosition());
        contact.setRemark(request.getRemark());
        contact.setCreateUserId(currentUserId);
        contact.setCreateAt(System.currentTimeMillis());
        contact.setDeleteStatus(DeleteStatus.NOT_DELETED);
        contact.setCustomer(customerRepository.findById(request.getCustomerId())
            .orElseThrow(() -> new ResourceNotFoundException("客户不存在")));

         contact = contactRepository.save(contact);
         User user = userService.getUserById(currentUserId);

         ContactDepartment contactDepartment = new ContactDepartment(contact,departmentRepository.findById(user.getDepartmentId())
         .orElseThrow(() -> new ResourceNotFoundException("部门不存在")));  
         contactDepartment.setCreateUserId(currentUserId);
         contactDepartment.setCreateAt(System.currentTimeMillis());
         contactDepartment = contactDepartmentRepository.save(contactDepartment);

         // 记录添加联系人日志
         customerLogService.logContactAdd(contact.getCustomer(), user, contact);

         return contact;
    }

    @Override
    @Transactional
    public Contact updateContact(Contact contact,Long currentUserId) {
        Contact existing = contactRepository.findById(contact.getId())
            .orElseThrow(() -> new ResourceNotFoundException("Contact not found with id: " + contact.getId()));
        
        existing.setName(contact.getName());
        existing.setPhone(contact.getPhone());
        existing.setEmail(contact.getEmail());
        existing.setPosition(contact.getPosition());
        existing.setRemark(contact.getRemark());
        existing.setUpdateUserId(currentUserId);
        existing.setUpdateAt(System.currentTimeMillis());
        
        existing = contactRepository.save(existing);
        
        // 记录更新联系人日志
        User operator = userService.getUserById(currentUserId);
        customerLogService.logContactUpdate(existing.getCustomer(), operator, existing, "更新联系人信息");
        
        return existing;
    }

    @Override
    @Transactional
    public void deleteContact(Long id,Long currentUserId) {
        Contact contact = contactRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Contact not found with id: " + id));
        contact.setDeleteStatus(DeleteStatus.DELETED);
        contactRepository.save(contact);
        
        // 记录删除联系人日志
        User operator = userService.getUserById(currentUserId);
        customerLogService.logContactDelete(contact.getCustomer(), operator, contact);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Contact> getCustomerContacts(Long customerId, Pageable pageable) {
        return contactRepository.findByCustomerId(customerId, DeleteStatus.NOT_DELETED, pageable);
    }

    @Override
    @Transactional
    public void addContactDepartment(Long contactId, Long departmentId,Long currentUserId) {
        Contact contact = contactRepository.findById(contactId)
            .orElseThrow(() -> new ResourceNotFoundException("Contact not found"));
        
        Department department = departmentRepository.findById(departmentId)
            .orElseThrow(() -> new ResourceNotFoundException("Department not found"));
        
        contact.getDepartments().add(department);
        contactRepository.save(contact);
    }

    @Override
    @Transactional
    public void removeContactDepartment(Long contactId, Long departmentId,Long currentUserId) {
        Contact contact = contactRepository.findById(contactId)
            .orElseThrow(() -> new ResourceNotFoundException("Contact not found"));
        
        Department department = departmentRepository.findById(departmentId)
            .orElseThrow(() -> new ResourceNotFoundException("Department not found"));
        
        contact.getDepartments().remove(department);
        contactRepository.save(contact);
    }

    @Override
    @Transactional
    public void clearContactDepartments(Long contactId,Long currentUserId) {
        Contact contact = contactRepository.findById(contactId)
            .orElseThrow(() -> new ResourceNotFoundException("Contact not found with id: " + contactId));
        
        // 清除所有部门关联
        contact.getDepartments().clear();
        contactRepository.save(contact);
    }
}
